package com.metacube.questionbank.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.metacube.questionbank.dto.AnswerDTO;
import com.metacube.questionbank.jdbc.AnswerRowMapper;

@Repository
public class AnswerDAO {

	@Autowired
	DataSource dataSource;

	public int insertAnswer(AnswerDTO qDTO) {

		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		String query = "insert into answer(QID, ABODY, USERID, ANSWEREDON, MODIFIEDDATE)"
				+ " values(?,?,?,?,?)";

		return (jdbcTemplate.update(
				query,
				new Object[] { qDTO.getqId(), qDTO.getaBody(),
						qDTO.getUserId(), qDTO.getAnsweredDate(),
						qDTO.getModifiedDate() }));
	}

	public List<AnswerDTO> getAnswers(int qId) {

		List<AnswerDTO> answerList = new ArrayList<AnswerDTO>();

		String query = "select * from answer where qID = ?";

		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

		answerList = jdbcTemplate.query(query, new Object[] { qId },
				new AnswerRowMapper());

		return answerList;
	}

	public List<AnswerDTO> getMyAnswersFromDB(int userId) {
		List<AnswerDTO> answerList = new ArrayList<AnswerDTO>();

		String query = "select a.aId, a.qId, a.userId, a.answeredOn, a.isAccepted, a.voteLike,"
				+ " a.aBody, a.isActive, a.modifieddate, q.Title, u.name"
				+ " from answer a, question q, user u where q.qId = a.qId and u.userId = a.userId and a.userId = ?";

		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

		answerList = jdbcTemplate.query(query, new Object[] { userId },
				new AnswerRowMapper());

		return answerList;

	}

	public List<AnswerDTO> getAnswersFromDB(int id) {
		List<AnswerDTO> answerList = new ArrayList<AnswerDTO>();
		System.out.println(id);
		String query = "select a.*, q.title, u.name from answer a, question q, user u where q.qId=? and u.userid = a.userid and q.qid = a.qid";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		answerList = jdbcTemplate.query(query, new Object[] {id},
				new AnswerRowMapper());
		System.out.println(answerList.get(0).getaId());
		return answerList;

	}

}
